/**
 * 测试用例状态 composable
 * 从状态管理模块获取测试用例状态选项
 */
import { computed } from 'vue'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/state'

export function useTestCaseStates() {
  const stateStore = useStateStore()

  // 获取测试用例状态列表
  const testCaseStates = computed(() => {
    return stateStore.getStatesByModule(ModuleType.TEST_CASE)
  })

  // 获取启用的测试用例状态
  const enabledStates = computed(() => {
    return testCaseStates.value.filter(state => state.is_enabled)
  })

  // 获取可见的测试用例状态
  const visibleStates = computed(() => {
    return testCaseStates.value.filter(state => state.is_visible)
  })

  // 获取默认状态
  const defaultState = computed(() => {
    return testCaseStates.value.find(state => state.is_default) || testCaseStates.value[0]
  })

  // 获取状态选项（用于下拉框）- 只返回启用且可见的状态
  const statusOptions = computed(() => {
    return enabledStates.value.filter(state => state.is_visible).map(state => ({
      value: state.code,
      label: state.name,
      color: state.color,
      icon: state.icon,
      disabled: false  // 因为是启用的状态，所以都不禁用
    }))
  })

  // 根据代码获取状态
  const getStateByCode = (code: string) => {
    return testCaseStates.value.find(state => state.code === code)
  }

  // 根据代码获取状态名称
  const getStateName = (code: string) => {
    const state = getStateByCode(code)
    return state?.name || code
  }

  // 根据代码获取状态颜色
  const getStateColor = (code: string) => {
    const state = getStateByCode(code)
    return state?.color || '#909399'
  }

  // 检查状态代码是否有效
  const isValidState = (code: string) => {
    return enabledStates.value.some(state => state.code === code)
  }

  // 加载状态数据
  const loadStates = async () => {
    try {
      console.log('开始加载测试用例状态...')
      await stateStore.fetchModuleStates(ModuleType.TEST_CASE)
      console.log('状态数据已加载，状态数量:', testCaseStates.value.length)
      console.log('可见状态数量:', visibleStates.value.length)
      console.log('状态选项数量:', statusOptions.value.length)
    } catch (error) {
      console.error('加载测试用例状态失败:', error)
      throw error
    }
  }

  return {
    testCaseStates,
    enabledStates,
    visibleStates,
    defaultState,
    statusOptions,
    getStateByCode,
    getStateName,
    getStateColor,
    isValidState,
    loadStates
  }
}

